
#include "dlist.h"
#include "stdlib.h"
#include "stddef.h"
#include "printf.h"

#define LIST_PRINTF printf_
#define list_malloc malloc
#define list_free free

//双向链表 ，非循环，带头部节点 
static List_item_t *list_item_create(Base_t data);

/*
 * 创建节点数据，申请内存，初始化数据data，指针归零，防止野指针
 */
static List_item_t *list_item_create(Base_t dat)
{
    List_item_t *item = (List_item_t *)list_malloc(sizeof(List_item_t));

    // 内存申请失败
    if (item == NULL)
    {
        LIST_PRINTF("err list item %d ", __LINE__);
    }

    // 初始化数据
    item->data = dat;

    // 指针归零,防止野指针
    item->next = NULL;
    item->previous = NULL;

    return item;
}

/*
 * 创建带头链表,头数据为0，长度为n
 */
List_item_t *list_create(Base_t data[], Base_t length)
{

    // 创建头部
    List_item_t *head = list_item_create(0);

    // 指针指向自身
    head->next = head;
    head->previous = head;
    List_item_t *item = head;
    List_item_t *newlist;
    for (Base_t i = 0; i < length; i++)
    {
        newlist = list_item_create(data[i]);
        item->next = newlist;
        newlist->previous = item;
        newlist->next=NULL;
        item = newlist;
    }
    return head;
}

// head下一个位置插入一个元素
List_item_t * list_insert(List_item_t *head, Base_t data)
{
    // 创建临时
    List_item_t *newlist = list_item_create(data);
    if (newlist == NULL)
    {
        LIST_PRINTF("err list insert %d ", __LINE__);
    }
    
    List_item_t *templist = head->next;
    
    head->next = newlist;
    
    newlist->next=templist;
    newlist->previous=head;
    
    templist->previous = newlist;
    return head;
}

// head下一个位置插入一个元素
void list_remove(List_item_t *head, Base_t dat)
{
    
     List_item_t *temp=head;
     
     for(;temp;temp=temp->next)
     {
       if(temp->data==dat)
       {
         break;
       }
     }
     
   List_item_t *front=temp->previous;
   List_item_t *back;
   if(temp->next!=NULL)
   {
      back=temp->next;
      back->previous=front;
      front->next=back;
   } 
   else
   {
      front->next=NULL;
   }
   
   
   list_free(temp);
}



void list_printf(List_item_t *head)
{
    List_item_t *temp = head->next;
    Base_t i = 0;
    for (; temp; temp = temp->next)
    {
        LIST_PRINTF("\r\nlist[%ld]:%ld \r\n", i, temp->data);
        i++;
    }
}

 